<template>
  <div class="chat-area" ref="messagesContainer">
    <div class="messages">
      <div v-if="messages.length <= 1" class="empty-state">
        <h2>开始新的对话</h2>
        <p>在下方输入框中输入你的问题</p>
      </div>
      <div v-for="(msg, index) in displayMessages" 
           :key="index" 
           :class="['message', msg.role]">
        <div class="avatar">
          {{ getAvatar(msg.role) }}
        </div>
        <div class="content">
          <div v-if="isLastAIMessage(index) && loading && !currentStreamingMessage" 
               class="thinking">
            <div class="dot-typing"></div>
          </div>
          <template v-else>
            <div v-if="msg.role === 'assistant'" 
                 class="markdown-body" 
                 v-html="formatMarkdown(msg.content)">
            </div>
            <div v-else>{{ msg.content }}</div>
          </template>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch, onUnmounted } from 'vue'
import { storeToRefs } from 'pinia'
import { useChatStore } from '../stores/chat'
import { marked } from 'marked'
import hljs from 'highlight.js'
import 'highlight.js/styles/github.css'

const chatStore = useChatStore()
const { messages, loading, currentStreamingMessage } = storeToRefs(chatStore)
const messagesContainer = ref(null)

// 基础配置
marked.setOptions({
  gfm: true,
  breaks: true,
  highlight: function (code, lang) {
    if (lang && hljs.getLanguage(lang)) {
      return hljs.highlight(code, { language: lang }).value
    }
    return code
  }
})

const displayMessages = computed(() => {
  return messages.value.filter(msg => msg.role !== 'system')
})

const getAvatar = (role) => {
  switch (role) {
    case 'user':
      return '🧑' // 用户头像
    case 'assistant':
      return '🤖' // AI助手头像
    default:
      return '❓' // 默认头像
  }
}

const isLastAIMessage = (index) => {
  return index === displayMessages.value.length - 1 && 
         displayMessages.value[index].role === 'assistant'
}

const formatMarkdown = (content) => {
  if (!content) return ''
  try {
    return marked.parse(String(content))
  } catch (err) {
    console.error('Markdown parsing error:', err)
    return String(content)
  }
}

// 自动滚动
const scrollToBottom = () => {
  if (messagesContainer.value) {
    messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight
  }
}

watch(() => messages.value.length, scrollToBottom)
watch(currentStreamingMessage, scrollToBottom)
onMounted(scrollToBottom)

// 添加复制功能
onMounted(() => {
  const addCopyButtons = () => {
    const codeBlocks = document.querySelectorAll('.content pre')
    codeBlocks.forEach((block) => {
      if (!block.querySelector('.code-copy-btn')) {
        // 创建代码语言标签和复制按钮的容器
        const header = document.createElement('div')
        header.className = 'code-header'
        
        // 获取代码语言
        const code = block.querySelector('code')
        const language = code?.className.split('-')[1] || 'text'
        
        // 添加语言标签
        const langTag = document.createElement('span')
        langTag.className = 'code-lang'
        langTag.textContent = language
        
        // 创建复制按钮
        const button = document.createElement('button')
        button.className = 'code-copy-btn'
        button.textContent = '复制'
        button.onclick = async () => {
          const codeText = code.textContent
          try {
            await navigator.clipboard.writeText(codeText)
            button.textContent = '已复制'
            setTimeout(() => {
              button.textContent = '复制'
            }, 2000)
          } catch (err) {
            console.error('复制失败:', err)
          }
        }
        
        // 组装并插入到代码块
        header.appendChild(langTag)
        header.appendChild(button)
        block.insertBefore(header, block.firstChild)
        
        // 调整代码块的内边距
        block.style.paddingTop = '2.5em'
      }
    })
  }

  // 监听内容变化
  const observer = new MutationObserver(addCopyButtons)
  observer.observe(messagesContainer.value, { 
    childList: true, 
    subtree: true 
  })

  // 初始化时添加按钮
  addCopyButtons()

  // 组件卸载时清理
  onUnmounted(() => {
    observer.disconnect()
  })
})
</script>

<style scoped>
.chat-area {
  flex: 1;
  overflow-y: auto;
  padding: 20px 0;
  max-width: 900px;
  margin: 0 auto;
  width: 100%;
  scrollbar-width: thin;
  scrollbar-color: rgba(0, 0, 0, 0.2) transparent;
}

.chat-area::-webkit-scrollbar {
  width: 8px;
}

.chat-area::-webkit-scrollbar-track {
  background: transparent;
}

.chat-area::-webkit-scrollbar-thumb {
  background-color: rgba(0, 0, 0, 0.2);
  border-radius: 4px;
  border: 2px solid transparent;
}

.chat-area::-webkit-scrollbar-thumb:hover {
  background-color: rgba(0, 0, 0, 0.3);
}

@media (prefers-color-scheme: dark) {
  .chat-area {
    scrollbar-color: rgba(255, 255, 255, 0.2) transparent;
  }

  .chat-area::-webkit-scrollbar-thumb {
    background-color: rgba(255, 255, 255, 0.2);
  }

  .chat-area::-webkit-scrollbar-thumb:hover {
    background-color: rgba(255, 255, 255, 0.3);
  }
}

.messages {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.message {
  display: flex;
  gap: 8px;
  padding: 0 16px;
  max-width: 100%;
}

.avatar {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  background: #e5e7eb;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 16px;
  flex-shrink: 0;
}

.content {
  flex: 1;
  padding: 8px 12px;
  background: #f8f5f1;
  color: #374151;
  border-radius: 6px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
  max-width: 70%;
  word-wrap: break-word;
  overflow-wrap: break-word;
  font-size: 14px;
  line-height: 1.5;
}

.user {
  flex-direction: row-reverse;
  justify-content: flex-start;
}

.user .avatar {
  background: #059669;
  color: white;
}

.user .content {
  background: #059669;
  color: #ffffff;
}

/* Markdown 样式 */
.content :deep(pre) {
  position: relative;
  background: #1e1e1e;
  color: #d4d4d4;
  margin: 6px 0;
  padding: 12px;
  padding-top: 40px; /* 为头部留出空间 */
  font-size: 13px;
  border-radius: 4px;
  max-height: 400px;
  overflow-x: auto;
  overflow-y: auto;
}

.content :deep(pre::-webkit-scrollbar) {
  width: 8px;
  height: 8px;
}

.content :deep(pre::-webkit-scrollbar-track) {
  background: rgba(0, 0, 0, 0.2);
  border-radius: 4px;
}

.content :deep(pre::-webkit-scrollbar-thumb) {
  background: rgba(255, 255, 255, 0.2);
  border-radius: 4px;
}

.content :deep(pre::-webkit-scrollbar-thumb:hover) {
  background: rgba(255, 255, 255, 0.3);
}

.content :deep(pre::-webkit-scrollbar-corner) {
  background: transparent;
}

.content :deep(pre code) {
  color: #d4d4d4;
  background: transparent;
  padding: 0;
  white-space: pre;
}

.user .content :deep(pre) {
  background: #1a1a1a;
  border: 1px solid rgba(255, 255, 255, 0.1);
}

.user .content :deep(:not(pre) > code) {
  background: rgba(0, 0, 0, 0.3);
  color: #ffffff;
}

.content :deep(code) {
  background: rgba(255, 255, 255, 0.7);
  color: #374151;
  padding: 2px 4px;
  border-radius: 4px;
}

.user .content :deep(code) {
  background: rgba(0, 0, 0, 0.2);
  color: #ffffff;
}

.content :deep(p) {
  margin: 6px 0;
}

.content :deep(ul),
.content :deep(ol) {
  padding-left: 16px;
  margin: 6px 0;
}

.content :deep(h1),
.content :deep(h2),
.content :deep(h3),
.content :deep(h4) {
  margin: 12px 0 6px;
  font-size: 1.1em;
}

.content :deep(blockquote) {
  border-left-color: #d1d5db;
  color: #6b7280;
}

.user .content :deep(blockquote) {
  border-left-color: rgba(255, 255, 255, 0.3);
  color: rgba(255, 255, 255, 0.8);
}

.content :deep(table) {
  margin: 6px 0;
  font-size: 13px;
}

.content :deep(td),
.content :deep(th) {
  padding: 6px;
}

.thinking .dot-typing {
  width: 4px;
  height: 4px;
  background: #666;
  border-radius: 50%;
  animation: dot-typing 1.5s infinite linear;
}

@keyframes dot-typing {
  0%, 100% { transform: scale(1); opacity: 1; }
  50% { transform: scale(0.5); opacity: 0.5; }
}

.content :deep(a) {
  color: #2563eb;
}

.user .content :deep(a) {
  color: #ffffff;
  text-decoration: underline;
}

@media (prefers-color-scheme: dark) {
  .content {
    background: #2d2d2d;
    color: #e5e7eb;
  }

  .content :deep(pre) {
    background: #1a1a1a;
    border: 1px solid rgba(255, 255, 255, 0.1);
  }

  .content :deep(code) {
    background: rgba(0, 0, 0, 0.3);
    color: #e5e7eb;
  }

  .content :deep(blockquote) {
    border-left-color: #4b5563;
    color: #9ca3af;
  }

  .content :deep(a) {
    color: #60a5fa;
  }
}

/* 代码块头部样式 */
.content :deep(.code-header) {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 6px 12px;
  background: #2d2d2d;
  border-bottom: 1px solid #3d3d3d;
  border-radius: 4px 4px 0 0;
}

/* 语言标签样式 */
.content :deep(.code-lang) {
  color: #888;
  font-size: 12px;
  font-family: monospace;
}

/* 复制按钮样式 */
.content :deep(.code-copy-btn) {
  padding: 2px 8px;
  font-size: 12px;
  color: #d4d4d4;
  background: #3d3d3d;
  border: 1px solid #4d4d4d;
  border-radius: 3px;
  cursor: pointer;
  transition: all 0.2s ease;
}

.content :deep(.code-copy-btn:hover) {
  background: #4d4d4d;
}

.content :deep(.code-copy-btn:active) {
  transform: scale(0.95);
}

/* 用户消息中的代码块样式调整 */
.user .content :deep(.code-header) {
  background: #1a1a1a;
  border-bottom-color: #2d2d2d;
}

.user .content :deep(.code-copy-btn) {
  background: #2d2d2d;
  border-color: #3d3d3d;
  color: #d4d4d4;
}

.user .content :deep(.code-copy-btn:hover) {
  background: #3d3d3d;
}
</style> 